package com.lxh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxh.entity.User;
import com.lxh.entity.dto.UserDto;
import com.lxh.entity.vo.UserVo;
import com.lxh.mapper.UserMapper;
import com.lxh.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lxh
 * @since 2022-03-01
 */
@RequiredArgsConstructor
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final UserMapper userMapper;

    @Override
    public List<UserVo> getList(UserDto dto) {
        ArrayList<UserVo> list = new ArrayList<>();
        this.list(getCondition(dto)).forEach(user -> {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            list.add(userVo);
        });

        return list;
    }

    @Override
    public IPage<UserVo> getPage(UserDto dto) {
        LambdaQueryWrapper<User> queryWrapper = getCondition(dto);
        Page<User> page = new Page<>(dto.getCurrentPage(), dto.getPageSize());
        IPage<User> pages = this.page(page, queryWrapper);
        return pages.convert(user -> {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            return userVo;
        });
    }

    /**
     * 查询条件
     * @param dto /
     * @return com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<com.lxh.entity.User> /
     * @author lxh
     * @date 2022/3/1 16:40
     */
    private LambdaQueryWrapper<User> getCondition(UserDto dto) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dto.getId() != null, User::getId, dto.getId())
                .like(StringUtils.isNotEmpty(dto.getName()), User::getName, dto.getName())
                .eq(dto.getAge() != null, User::getAge, dto.getAge())
                .between(dto.getBeginAge() != null && dto.getEndAge() != null, User::getAge, dto.getBeginAge(), dto.getEndAge())
                .orderByAsc(User::getAge);
        return queryWrapper;
    }


}
